// 1.匹配不以'/'或者'.html'结尾的请求，并重定向到以斜杠结尾的情况
const express = require('express')
const path = require('path')
const config = require('../config/env')
const resolve = file => path.resolve(__dirname, file)
const storeHtml = require(resolve('../server/storeHtml'))
const axios = require('axios')
const schedule = require('../schedule/schedule')

let options = {
  baseURL:  config.serverApiUrl.url,
  timeout: 6000,
}
if (config.serverApiUrl.host) {
  options.headers = {'Host':config.serverApiUrl.host}
}
let instance = axios.create(options)

let router = express.Router()
// 请求参数设置

function handleAc(req, res) {
  let key = 'ac'

  let url = req.url
  // 支持ac页面链接后面带斜杠
  if (url.endsWith('/')) {
    url = url.slice(0, url.lastIndexOf('/'))
  }
  if (url.indexOf('?') > -1) {
    //兼容qq浏览器打开带参数
    url = url.split('?')[0]
  }
  let path_str = '/' + key
  let html_name = url.substring(url.indexOf(path_str) + path_str.length).replace('/', '') //获取html_name
  // 去掉html_name中的非法斜杠
  html_name = html_name.replace(/\//g, '')
  let terminal = url.substring(0, url.indexOf(path_str)).replace('/', '')
  let api_url = `/newsapi/api/html?template=${key}&html_name=${html_name}`

  let responseTime = Date.now() - req.xRequest.time// ms单位

  let cacheKey = key + '_' + html_name
  let cacheValue = storeHtml.getAcItem(cacheKey)
  if (cacheValue) {
    res.setHeader('X-Request-Id', req.xRequest.id+'-'+responseTime+'-0');
    return res.send(cacheValue)
  }

  instance.get(api_url).then(response => {
    let { status, data} = response
    if (status !== 200) {
      return res.status(502).end()
    }
    if (+data.errcode !== 0) {
      return res.status(404).end()
    }
    let htmls = data.data
    let html_cont = ''
    if (htmls.length <= 1) {
      html_cont = htmls[0].html
    } else {
      for (let j = 0; j < htmls.length; j++) {
        const html = htmls[j]
        if (html.terminal == terminal) {
          html_cont = html.html
        }
      }
    }
    storeHtml.setAcItem(cacheKey, html_cont)
    res.setHeader('X-Request-Id', req.xRequest.id+'-'+responseTime+'-1');
    return res.send(html_cont)
  }).catch(err => {
    return res.status(502).end()
  })
}

/* 代理部分请求，主要用于代理点赞等接口*/
function handleProxy(req, res) {
  if (req.method.toUpperCase() !== 'GET') {
    return res.status(404).end()
  }

  let url = req.url
  let subUrl = url.replace('/proxy', '') //只代理newsapi的接口

  if (subUrl.startsWith('/schedule/pull')) {//验证sitemap推接口
    schedule.startPull(function(result) {
      res.end(result?JSON.stringify(result):'')
    })
    return
  } else if (subUrl.startsWith('/schedule/push')) {//验证sitemap拉接口
    schedule.startPush(function(result) {
      res.end(result?JSON.stringify(result):'')
    })
    return
  } else if (!subUrl.startsWith('/newsapi/')) {//非newsapi不代理
    return res.status(404).end()
  }
  /*代理接口*/
  instance.get(subUrl).then(response => {
    let { status, data} = response

    if (status !== 200) {
      return res.status(502).end()
    }

    try {
      let result = JSON.stringify(data)
      return res.send(result)
    } catch(err) {
      return res.status(502).end()
    }

  }).catch(err => {
    return res.status(502).end()
  })
}


let specialRouter = {
  ac: {
    route:`/ac/:pathname/`,
    func:handleAc
  },
  proxy:{
    route:`/proxy/*`,
    func:handleProxy
  }
}

/*注册路由*/
for (const key in specialRouter) {
  if (!specialRouter.hasOwnProperty(key)) continue
  let handle  = specialRouter[key]
  router.get(handle.route, handle.func)
}

module.exports = router
